package com.feng.sharedingjdbc.config;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.sharding.spi.KeyGenerateAlgorithm;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.Properties;

/**
 * 自定义分布式id生成算法
 * @author yinglong.zhang
 * @date 2024-1-23 17:59
 */
//@Component
@Slf4j
public class UserIdKeyGenerator implements KeyGenerateAlgorithm, ApplicationContextAware {
    @Getter
    @Setter
    private Properties properties;

    public static RedisTemplate redisTemplate;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        redisTemplate = applicationContext.getBean(StringRedisTemplate.class);
    }


    @Override
    public Comparable<?> generateKey() {
        ValueOperations valueOp = redisTemplate.opsForValue();
        return  valueOp.increment("sharding:uid", 1);
    }


    @Override
    public String getType() {
        return "autoIncrement";
    }

    @Override
    public void init(Properties props) {

    }

    @Override
    public Properties getProps() {
        return null;
    }
}
